'use strict';

const BaseController = require('../../core/base_controller');

class CoverShiftController extends BaseController {
    async userView() {
        const {ctx} = this;
        const {id} = ctx.params;
        const {user_id} = ctx.request.headers
        let data = await ctx.model.CoverShift.findByPk(id)
        if (!data) {
            ctx.throw(500, '该数据不存在')
        }
        // 当企业发布的职位用户浏览的情况下
        if (data.user_id !== user_id) {
            let isBrowse = await ctx.model.UserBrowse.findOne({
                where: {browse_id: id, user_id, type: 'shift_work'}
            })
            if (!isBrowse) {
                await ctx.model.UserBrowse.create({
                    browse_id: id,
                    type: 'shift_work',
                    user_id
                })
            }
        }
        this.success()
    }

    async userCollect() {
        const {ctx} = this;
        const {id} = ctx.params;
        const {user_id} = ctx.request.headers
        let data = await ctx.model.CoverShift.findByPk(id)
        if (!data) {
            ctx.throw(500, '该职位不存在')
        }
        if (data.user_id !== user_id) {
            let isCollect = await ctx.model.UserCollect.findOne({
                where: {collect_id: id, user_id, type: 'shift_work'}
            })
            if (!isCollect) {
                await ctx.model.UserCollect.create({
                    collect_id: id,
                    type: 'shift_work',
                    user_id
                })
            } else {
                await isCollect.destroy()
            }
        }

        this.success()
    }

    // 获取代替班列表
    async index() {
        const {ctx} = this;
        const {user_id} = ctx.request.headers
        const {page = 1, pageSize = 10, status = 1, is_recruit = true, filterUserId} = ctx.query;
        // 构建查询条件
        const where = {
            del_flag: 0,
        };

        if (status) where.status = status;
        if (is_recruit) where.is_recruit = is_recruit;
        if (filterUserId) where.user_id = user_id
        const {count, rows} = await ctx.model.CoverShift.findAndCountAll({
            where,
            order: [['created_at', 'DESC']],
            offset: (page - 1) * pageSize,
            limit: parseInt(pageSize),
            include: [{
                model: ctx.model.User,
                attributes: ['real_name', 'avatar', 'sex', 'birth_day', 'phone'],
            },
                {model: ctx.model.Position, as: 'position', attributes: ['name', 'id']},
                {
                    model: ctx.model.DictionaryDetail,
                    as: 'workExperience',
                    attributes: ['dict_value', 'dict_key', 'id']
                }],
        });
        for (let item of rows) {
            item = item.dataValues;
            let ids = item.cuisine_ids ? item.cuisine_ids.split(',') : []
            item.cuisines = await ctx.model.DictionaryDetail.findAll({
                where: {
                    dict_key: {
                        [ctx.model.Sequelize.Op.in]: ids
                    }
                },
                attributes: ['dict_value', 'dict_key', 'id']
            })
        }
        this.success({
            list: rows,
            pagination: {
                total: count,
                current: parseInt(page),
                pageSize: parseInt(pageSize),
            },
        });
    }

    async updateStatus() {
        const {ctx} = this;
        const {id} = ctx.request.body;
        const job = await ctx.model.CoverShift.findByPk(id)
        if (!job) {
            ctx.throw(500, '该数据不存在')
        }
        await job.update({status: !job.status})
        this.success()
    }

    // 创建代替班
    async create() {
        const {ctx} = this;
        const {user_id} = ctx.request.headers;

        // 参数验证规则
        const rules = {
            position_id: {type: 'string', required: true},
            location: {type: 'string', required: true},
            cuisine_ids: {type: 'string', required: true},
            work_experience_id: {type: 'string', required: true},
            price_of_day: {type: 'string', required: true},
            connect_phone: {type: 'string', required: true},
        };

        try {
            ctx.validate(rules);
        } catch (err) {
            ctx.throw(400, '参数校验失败');
        }

        const data = {
            ...ctx.request.body,
            user_id,
            status: 1
        };

        const coverShift = await ctx.model.CoverShift.create(data);
        this.success(coverShift.id);
    }

    // 更新代替班信息
    async update() {
        console.log('update')
        const {ctx} = this;
        const {id} = ctx.params;
        // 参数验证规则
        const rules = {
            position_id: {type: 'string', required: true},
            location: {type: 'string', required: true},
            cuisine_ids: {type: 'string', required: true},
            work_experience_id: {type: 'string', required: true},
            price_of_day: {type: 'string', required: true},
            connect_phone: {type: 'string', required: true},
        };
        const coverShift = await ctx.model.CoverShift.findOne({
            where: {
                id
            },
        });
        try {
            ctx.validate(rules);
        } catch (err) {
            ctx.throw(400, '参数校验失败');
        }
        if (!coverShift) {
            ctx.throw(404, '代替班信息不存在');
        }
        await coverShift.update(ctx.request.body);
        this.success(coverShift);
    }

    // 删除代替班信息
    async destroy() {
        const {ctx} = this;
        const user_id = ctx.state.user.id;
        const {id} = ctx.params;

        const coverShift = await ctx.model.CoverShift.findOne({
            where: {
                id,
                user_id,
                del_flag: 0,
            },
        });

        if (!coverShift) {
            ctx.throw(404, '代替班信息不存在');
        }

        // 已发布或进行中的不能删除
        if ([1, 2].includes(coverShift.status)) {
            ctx.throw(400, '当前状态不能删除');
        }

        await coverShift.update({del_flag: 1});
        this.success(null, '删除成功');
    }

    // 获取代替班详情
    async show() {
        const {ctx} = this;
        const {id} = ctx.params;
        const {user_id} = ctx.request.headers;
        let coverShift = await ctx.model.CoverShift.findOne({
            where: {
                id,
                del_flag: 0,
            },
            include: [
                {
                    model: ctx.model.User,
                    attributes: ['real_name', 'avatar', 'sex', 'birth_day', 'phone'],
                },
                {model: ctx.model.Position, as: 'position', attributes: ['name', 'id']},
                {model: ctx.model.DictionaryDetail, as: 'workExperience', attributes: ['dict_value', 'dict_key', 'id']},
            ],
        });
        if (!coverShift) {
            ctx.throw(404, '代替班信息不存在');
        }
        coverShift = coverShift.dataValues
        let ids = coverShift.cuisine_ids ? coverShift.cuisine_ids.split(',') : []
        coverShift.cuisines = await ctx.model.DictionaryDetail.findAll({
            where: {
                dict_key: {
                    [ctx.model.Sequelize.Op.in]: ids
                }
            },
            attributes: ['dict_value', 'dict_key', 'id']
        })
        coverShift.is_collect = !!await ctx.model.UserCollect.findOne({
            where: {user_id, type: 'shift_work', collect_id: coverShift.id},
        })
        this.success(coverShift);
    }

}

module.exports = CoverShiftController;
